package com.hhs.storage.controller;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.service.*;
import com.hhs.storage.util.NumberUtil;
import com.hhs.storage.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yuanjun
 * @since 2020-08-15
 */
@RestController
@RequestMapping("/app/yymhuiyuantc")
@Slf4j
public class AppYymHuiyuanTcController {
    @Resource
    YymHuiyuanTcService yymHuiyuanTcService;
    @Resource
    JxcMenuService jxcMenuService;
    @Resource
    JxcRoleUserService jxcRoleUserService;
    @Resource
    YymUserTcLinkService yymUserTcLinkService;
    @Resource
    YymPayOrderService yymPayOrderService;

    @RequestMapping(value = "getAll")
    public Map<String, Object> getAll(InputParam inputParam) {
        log.info("查询会员套餐信息");
        EntityWrapper<YymHuiyuanTc> ew = new EntityWrapper<>();
        ew.orderBy("name_", true);
        Page<YymHuiyuanTc> result = yymHuiyuanTcService.selectPage(new Page<YymHuiyuanTc>(inputParam.getPage(), inputParam.getSize()), ew);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", result.getRecords());
        map.put("total", result.getTotal());
        return map;
    }

    @RequestMapping(value = "getTcMenu")
    public Map<String, Object> getTcMenu(InputParam inputParam) {
        log.info("查询套餐可以访问的菜单");
        List<JxcMenu> list = jxcMenuService.findByRoleId(inputParam.getRoleid());
        return Result.sucJsonResp(list);
    }

    @RequestMapping(value = "getorder")
    public Map<String, Object> getorder(String tcid, String userid) throws Exception {
        log.info("查询套餐数据生成定单");
        List<YymHuiyuanTc> list = yymHuiyuanTcService.selectList(new EntityWrapper<YymHuiyuanTc>().eq("id_", tcid));
        if (list.size() != 1) {
            return Result.failJsonResp("定单错误");
        }
        YymHuiyuanTc yht = list.get(0);
        //生成一个新订单
        YymPayOrder ypo = new YymPayOrder();
        ypo.setCreateTime(new Date());
        ypo.setExcZfje(yht.getPrice()*100);
        ypo.setReaZfje(0);
        ypo.setUserId(userid);
        ypo.setTcId(tcid);
        ypo.setZfsm(yht.getName() + "-" + yht.getFlag());
        ypo.setIsOk(0);
        yymPayOrderService.insert(ypo);
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", ZfbOrderBean.APP_ID, ZfbOrderBean.APP_PRIVATE_KEY, "json", "utf-8", ZfbOrderBean.ALIPAY_PUBLIC_KEY, "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("套餐购买");
        model.setSubject(ypo.getZfsm());
        model.setOutTradeNo(ypo.getId());
        model.setTimeoutExpress("50m");
        model.setTotalAmount("0.01");
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl("http://123.57.10.242/app/yymhuiyuantc/zfbcallback");
        String data = "";
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            data = response.getBody();//就是orderString 可以直接给客户端请求，无需再做处理。
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return Result.sucJsonResp(data);
    }

    @RequestMapping(value = "zfbcallback")
    public String zfbcallback(HttpServletRequest request) throws AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        boolean flag = AlipaySignature.rsaCheckV1(params, ZfbOrderBean.ALIPAY_PUBLIC_KEY, "utf-8", "RSA2");
        System.out.println("支付宝"+flag+" callback"+params);
        /**
         * 接收的参数形式
         * {
         gmt_create=2020-08-2520: 13: 02,
         charset=utf-8,
         seller_email=2754293166@qq.com,
         subject=套餐1-vip1,
         body=套餐购买,
         buyer_id=2088512925581556,
         invoice_amount=0.01,
         notify_id=2020082500222201304081550584599500,
         fund_bill_list=[
         {
         "amount": "0.01",
         "fundChannel": "ALIPAYACCOUNT"
         }
         ],
         notify_type=trade_status_sync,
         trade_status=TRADE_SUCCESS,
         receipt_amount=0.01,
         app_id=2021001189692233,
         buyer_pay_amount=0.01,
         seller_id=2088931174755792,
         gmt_payment=2020-08-2520: 13: 03,
         notify_time=2020-08-2520: 13: 04,
         version=1.0,
         out_trade_no=f7d6101c835b42db8edd3225bc4e5204,
         total_amount=0.01,
         trade_no=2020082522001481550549698277,
         auth_app_id=2021001189692233,
         buyer_logon_id=187****0028,
         point_amount=0.00
         }
         */
        if(flag==true){
            //修改数据库表
            String orderid=params.get("out_trade_no");
            List<YymPayOrder> list = yymPayOrderService.selectList(new EntityWrapper<YymPayOrder>().eq("id_", orderid));
            if(list.size()==1){
                YymPayOrder order = list.get(0);
                order.setIsOk(1);
                order.setPayTime(new Date());
                double zfje=NumberUtil.toDoubleCase(params.get("buyer_pay_amount"))*100;
                order.setReaZfje(NumberUtil.toIntCase(zfje+""));
                yymPayOrderService.insertOrUpdate(order);

                List<YymHuiyuanTc> tclist = yymHuiyuanTcService.selectList(new EntityWrapper<YymHuiyuanTc>().eq("id_", order.getTcId()));
                if(tclist.size()==1){
                    InputParam input=new InputParam();
                    input.setUserid(order.getUserId());
                    input.setRoleid(tclist.get(0).getRoleId());
                    input.setTcid(order.getTcId());
                    changeRole(input);
                }
                return "success";
            }
        }
        return "failure";
    }

    private Map<String, Object> changeRole(InputParam inputParam) {
        log.info("vip的客户换角色");
        String roleid = inputParam.getRoleid();
        String userid = inputParam.getUserid();
        if (StringUtils.isEmpty(roleid) || StringUtils.isEmpty(userid)) {
            return Result.failJsonResp(null);
        }
        JxcRoleUser jru = new JxcRoleUser();
        jru.setUserId(inputParam.getUserid());
        jru.setRoleId(inputParam.getRoleid());
        jru.setCreateTime(new Date());
        EntityWrapper<JxcRoleUser> ew = new EntityWrapper<>();
        ew.eq("user_id_", userid);
        jxcRoleUserService.delete(ew);
        jxcRoleUserService.insertOrUpdate(jru);
        EntityWrapper<YymUserTcLink> ew2 = new EntityWrapper<>();
        ew2.eq("user_id_", userid);
        yymUserTcLinkService.delete(ew2);
        YymUserTcLink yymUTL = new YymUserTcLink();
        yymUTL.setCreateTime(new Date());
        yymUTL.setTcId(inputParam.getTcid());
        yymUTL.setUserId(inputParam.getUserid());
        yymUserTcLinkService.insert(yymUTL);
        return Result.sucJsonResp(null);
    }
}

